public class HashBucket2<K,V> {
    static class Node<K,V>{
        public K key;
        public V value;
        public Node<K,V> next;
        public Node(K key,V value) {
            this.key = key;
            this.value = value;
        }
    }
    public Node<K,V>[] array = (Node<K,V>[])new Node[10];
    public int usedSize;

    // 负载因子最大值
    public static final double LOAD_FACTOR = 0.75;


    // 插入数据
    public void put(K key,V value) {
        // 计算位置
        int hash = key.hashCode();
        int index = hash % array.length;
        Node<K,V> cur = array[index];

        while (cur != null) {
            if (cur.key.equals(key)) {
                // key已经存在，替换
                cur.value = value;
                return;
            }
            cur = cur.next;
        }

        // 头插法
        Node<K,V> node = new Node<>(key,value);
        node.next = array[index];
        array[index] = node;
        usedSize++;

        if (calculateLoadFactor() >= LOAD_FACTOR) {
            // 扩容
            resize();
        }
    }

    // 计算负载因子
    public double calculateLoadFactor() {
        return usedSize*1.0 / array.length;
    }

    // 扩容
    private void resize() {
        Node<K,V>[] newArray = (Node<K,V>[])new Node[2*array.length];
        // 遍历数组
        for (int i = 0; i < array.length; i++) {
            Node<K,V> cur = array[i];
            while (cur != null) {
                // 计算在新数组中的位置
                int hash = cur.key.hashCode();
                int index = hash % newArray.length;

                // 记录下个结点
                Node<K,V> curNext = cur.next;

                // 头插法
                cur.next = newArray[index];
                newArray[index] = cur;

                cur = curNext;
            }
        }
        array = newArray;
    }

    // 通过key返回对应value
    public V get(K key) {
        // 计算位置
        int hash = key.hashCode();
        int index = hash % array.length;
        Node<K,V> cur = array[index];
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur.value;
            }
            cur = cur.next;
        }
        return null;
    }
}

